<template>
  <el-dialog
    v-model="dialogVisible"
    title="流动人口录入"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 人员基本信息 -->
      <el-divider content-position="left">人员基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input 
              v-model="form.idCard" 
              placeholder="请输入身份证号"
              @blur="handleIdCardBlur"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input 
              v-model="personInfo.name" 
              placeholder="根据身份证号自动获取"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="personInfo.name">
        <el-col :span="8">
          <el-form-item label="性别">
            <el-input 
              :value="personInfo.gender === 1 ? '男' : personInfo.gender === 2 ? '女' : ''"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生日期">
            <el-input 
              :value="formatDate(personInfo.birthDate)"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话">
            <el-input 
              v-model="personInfo.phone"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 流动人口信息 -->
      <el-divider content-position="left">流动人口信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="居住类型" prop="residenceType">
            <el-select v-model="form.residenceType" placeholder="请选择居住类型" style="width: 100%">
              <el-option label="暂住" :value="1" />
              <el-option label="长期居住" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="现居住地址" prop="currentAddress">
            <el-input v-model="form.currentAddress" placeholder="请输入现居住地址" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="居住开始日期" prop="residenceStartDate">
            <el-date-picker
              v-model="form.residenceStartDate"
              type="date"
              placeholder="请选择居住开始日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="请输入备注信息（可选）" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="房东姓名">
            <el-input v-model="form.landlordName" placeholder="请输入房东姓名（可选）" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房东电话">
            <el-input v-model="form.landlordPhone" placeholder="请输入房东电话（可选）" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="就业状况">
            <el-select v-model="form.employmentStatus" placeholder="请选择（可选）" style="width: 100%">
              <el-option label="就业" :value="1" />
              <el-option label="失业" :value="2" />
              <el-option label="学生" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用工单位">
            <el-input v-model="form.employerName" placeholder="请输入用工单位（可选）" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="用工单位地址">
        <el-input v-model="form.employerAddress" placeholder="请输入用工单位地址（可选）" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确认录入
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref()
const loading = ref(false)

// 对话框显示状态（支持 v-model）
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 人员基本信息
const personInfo = reactive({
  name: '',
  gender: null,
  birthDate: '',
  phone: ''
})

// 表单数据 - 对应 FloatingPopulationBO
const form = reactive({
  idCard: '',
  residenceType: null,
  currentAddress: '',
  residenceStartDate: null,
  landlordName: '',
  landlordPhone: '',
  employmentStatus: null,
  employerName: '',
  employerAddress: '',
  remark: ''
})

// 验证规则
const rules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  residenceType: [
    { required: true, message: '请选择居住类型', trigger: 'change' }
  ],
  currentAddress: [
    { required: true, message: '请输入现居住地址', trigger: 'blur' }
  ],
  residenceStartDate: [
    { required: true, message: '请选择居住开始日期', trigger: 'change' }
  ]
}

const formatDate = (date) => {
  if (!date) return ''
  try { return new Date(date).toLocaleDateString() } catch { return '' }
}

// 身份证号失焦事件 - 获取人员信息
const handleIdCardBlur = async () => {
  if (!form.idCard || form.idCard.length !== 18) return
  try {
    const token = localStorage.getItem('token')
    if (!token) { ElMessage.error('请先登录'); return }
    const response = await axios.get(`${API_BASE_URL}/person/getByIdCard`, {
      params: { idCard: form.idCard },
      headers: { 'token': token }
    })
    if (response.data.status === 200 && response.data.data) {
      const person = response.data.data
      personInfo.name = person.name || ''
      personInfo.gender = person.gender || null
      personInfo.birthDate = person.birthDate || ''
      personInfo.phone = person.phone || ''
    } else {
      ElMessage.warning('未找到该身份证号对应的人员信息')
      personInfo.name = ''
      personInfo.gender = null
      personInfo.birthDate = ''
      personInfo.phone = ''
    }
  } catch (error) {
    console.error('获取人员信息失败:', error)
    ElMessage.error('获取人员信息失败')
  }
}

// 提交录入
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!personInfo.name) {
      ElMessage.error('请先输入有效的身份证号获取人员信息')
      return
    }
    loading.value = true
    try {
      const token = localStorage.getItem('token')
      if (!token) { ElMessage.error('请先登录'); return }
      const response = await axios.post(`${API_BASE_URL}/floatingPopulation/input`, form, {
        headers: { 'token': token, 'Content-Type': 'application/json' }
      })
      const result = response.data
      if (result.status === 200) {
        ElMessage.success(result.msg || '录入成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(result.msg || '录入失败')
      }
    } catch (error) {
      console.error('流动人口录入请求出错:', error)
      if (error.response) {
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        ElMessage.error('录入失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 关闭对话框并重置
const handleClose = () => {
  formRef.value?.resetFields()
  personInfo.name = ''
  personInfo.gender = null
  personInfo.birthDate = ''
  personInfo.phone = ''
  dialogVisible.value = false
}

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    setTimeout(() => {
      formRef.value?.resetFields()
      personInfo.name = ''
      personInfo.gender = null
      personInfo.birthDate = ''
      personInfo.phone = ''
    }, 300)
  }
})
</script>

<style lang="scss" scoped>
.el-divider {
  margin: 20px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>